//
//  MapViewController.m
//  MapApp
//
//  Created by Joe 'Suds' Paul on 04/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//


#import "MapAppViewController_iPhone.h"
#import "MapAppBuilding.h"
#import "MapAppAddressAnnotation.h"
#import "MapAppPDFViewController_iPhone.h"


@implementation MapAppViewController_iPhone

@synthesize mapView, mapAppPDFViewController, buildingName;

- (MapAppModalViewController_iPhone *) mapAppModalViewController_iPhone {
    if ( mapAppModalViewController_iPhone == nil ) {
        mapAppModalViewController_iPhone = [[MapAppModalViewController_iPhone alloc] initWithStyle:UITableViewStylePlain];
        mapAppModalViewController_iPhone.delegate = self;
        mapAppModalViewController_iPhone.title = @"Choose a building:";
		mapAppModalViewController_iPhone.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    }
    return mapAppModalViewController_iPhone;
}


- (UINavigationController *) buildingListNavigationController {
    if (buildingListNavigationController == nil) {
        buildingListNavigationController = [[UINavigationController alloc] initWithRootViewController:self.mapAppModalViewController_iPhone];
    }
    return buildingListNavigationController;
}



//- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation {
//	MKPinAnnotationView *pin = (MKPinAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier: @"asdf"];
//	if (pin == nil)
//	{
//		pin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier: @"asdf"] autorelease];
//	}
//	else
//	{
//		pin.annotation = annotation;
//	}
//	pin.pinColor = MKPinAnnotationColorRed;
//	pin.animatesDrop=TRUE;
//	pin.canShowCallout = YES;
//	pin.calloutOffset = CGPointMake(-5, 5);
//	return pin;
//}


- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation {  
	if ([annotation isKindOfClass:[MKUserLocation class]])
	{
		((MKUserLocation *)annotation).title = @"Current location";
		return nil; //return nil to use default blue dot view
	}
    MKPinAnnotationView *annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyPin"];

	UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	annView.rightCalloutAccessoryView = rightButton;

    annView.animatesDrop = TRUE;  
    annView.canShowCallout = YES;
    [annView setSelected:YES];
    annView.pinColor = MKPinAnnotationColorRed;  
    annView.calloutOffset = CGPointMake(-5, 5);  
    return annView;  
} 


- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
	// start the pdf viewer listening for the notification to send the name of the building
	[[NSNotificationCenter defaultCenter] addObserver:mapAppPDFViewController selector:@selector(eventHandler:) name:@"eventType" object:nil];	
	
	// trigger notification
	[[NSNotificationCenter defaultCenter] postNotificationName:@"eventType" object:buildingName];
	
	// stop listening
	[[NSNotificationCenter defaultCenter] removeObserver:mapAppPDFViewController];
	
	
	[[self navigationController] pushViewController:mapAppPDFViewController animated:YES];
}



/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */


- (void)viewDidLoad {
	[super viewDidLoad];
	self.title = @"Campus Map";
	
	// this line makes the nav bar's back button on the PDF viewer say Map, instead of the overly long building name
	self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Map" style: UIBarButtonItemStyleBordered target:nil action:nil];
		
	//self.view.frame = [[UIScreen mainScreen] applicationFrame];
	
	mapView.showsUserLocation=TRUE;
	MKCoordinateRegion region;
	CLLocationCoordinate2D coordinate;
	coordinate.latitude = 34.0411;
	coordinate.longitude = -118.711;
    region.center = coordinate;
    MKCoordinateSpan span = {0.01, 0.01};
    region.span = span;
    [mapView setRegion:region animated:YES];

	
	// check this section for memory leaks - is toolbar ever being released?  -Aaron
	//	toolbar = [UIToolbar new];
	//	toolbar.barStyle = UIBarStyleDefault;
	//	[toolbar sizeToFit];
	//	toolbar.frame = CGRectMake(0, 430, 320, 50);
	
	
//	
	// now create a Bar button item
	UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithTitle:@"Buildings" style:UIBarButtonItemStylePlain target:self action:@selector(showBuildingList:)];
	
	// set the nav bar's right button item
	self.navigationItem.rightBarButtonItem = item;
	[item release];
}



- (IBAction) showBuildingList:(id)sender{
	[self.navigationController presentModalViewController:self.buildingListNavigationController animated:YES];
}


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


- (void)animateToWorld:(MapAppBuilding *)building
{    
    MKCoordinateRegion current = mapView.region;
    MKCoordinateRegion zoomOut = { { (current.center.latitude + building.coordinate.latitude)/2.0 , (current.center.longitude + building.coordinate.longitude)/2.0 }, {.01, .01} };
    [mapView setRegion:zoomOut animated:YES];
}

- (void)animateToPlace:(MapAppBuilding *)building
{
    MKCoordinateRegion region;
    region.center = building.coordinate;
    MKCoordinateSpan span = {0.0008, 0.0008};
    region.span = span;
    [mapView setRegion:region animated:YES];
}


- (void)mapAppModalViewController_iPhone:(MapAppModalViewController_iPhone *)controller didChooseBuilding:(MapAppBuilding *)aBuilding
{
    [self.navigationController dismissModalViewControllerAnimated:YES];
    
	
	buildingName = aBuilding.name;
	
	
	// get rid of the previous annotation, leaving current location annotation
	[self.navigationController dismissModalViewControllerAnimated:YES];
	self.title = aBuilding.name;
	NSLog(@"Annotations: %@", mapView.annotations);
	NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:10];
	for (id annotation in mapView.annotations)
		if (annotation != mapView.userLocation)
			[toRemove addObject:annotation];
	[mapView removeAnnotations:toRemove];

	
	CLLocationCoordinate2D location;
	location.latitude = aBuilding.coordinate.latitude;
	location.longitude = aBuilding.coordinate.longitude;
	
	MapAppAddressAnnotation *addAnnotation = [[[MapAppAddressAnnotation alloc] initWithCoordinate:location] retain];
	
	
	[addAnnotation setTitle:aBuilding.name];
	[mapView addAnnotation:addAnnotation];
			
	
//	  Old code to zoom out before zooming back in to the selected building
    MKCoordinateRegion current = mapView.region;
    if (current.span.latitudeDelta < .01) {
        [self performSelector:@selector(animateToWorld:) withObject:aBuilding afterDelay:1.0];
        [self performSelector:@selector(animateToPlace:) withObject:aBuilding afterDelay:3.0];
    }
    else
    {
        [self performSelector:@selector(animateToPlace:) withObject:aBuilding afterDelay:1.0];
    }	
}

-(void)viewWillAppear:(BOOL)animated {
	mapAppPDFViewController.toolbar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.mapView = nil;
}


- (void)dealloc {
    [mapView release];
    [mapAppModalViewController_iPhone release];
    [buildingListNavigationController release];
	
    [super dealloc];
}


@end
